const ArticleModel = require('../../model/ArticleModel');

// 上传文章数据
const postArticle = async (req, res) => {
    let { u_id, username, u_photo, content, imgage_beas, author, aut_from } = req.body
    try {
        let re = await ArticleModel.create({
            u_id,
            username,
            u_photo,
            content,
            imgage_beas,
            author,
            aut_from
        });
        //   console.log('----', re);
        res.json({
            status: 200,
            message: "发表文章成功!"
        });
    } catch (err) {
        //   console.log(err);
        res.json({
            status: 400,
            message: "系统异常稍后重试!"
        })
    }
};
// 获取文章数据
const allArticle = async (req, res) => {
    console.log(' req.body', req.body);
    let { page, limit } = req.body;
    //  当前所有文章   skip(2) 跳过两条数据  limit(3) 取出结果里面前面3条
    let result = await ArticleModel.find({}).sort({ datetime: -1 }).skip((page - 1) * limit).limit(limit);
    //  当前所有文章总数
    let total = await ArticleModel.find({}).countDocuments();
    //  当前页码数据
    //  判断数据是否还有
    let dataStatus = true;
    if (page * limit >= total) {
        dataStatus = false
    }
    console.log('所有文章----->', total, dataStatus);
    //  console.log('所有文章----->', page, limit, total);
    res.json({
        status: 200,
        data: {
            result,
            total, //总数
            "dataStatus": dataStatus, //是否还有数据
        }
    })
};
// 获取当前用户发表的文章
const userArticle = async (req, res) => {
    let { u_id } = req.body;
    try {
        let user_result = await ArticleModel.where({
            u_id
        }).find().sort({ datetime: -1 });
        res.json({
            status: 200,
            message: '获取文章数据成功！',
            user_result
        })
    } catch (err) {
        console.log('获取数据失败！', err);
        res.json({
            status: 500,
            message: '获取数据失败！'
        })
    }
}
// 搜索
const searchArticle = async (req, res) => {
    let { keyword, page, limit } = req.body;
    console.log('搜索---->', keyword, page, limit);
    // 当前总数
    let seaTotal = await ArticleModel.where({
        content: new RegExp(keyword, "gi")
    }).countDocuments();
    // 分页
    let seaResult = await ArticleModel.where({
        content: new RegExp(keyword, "gi")
    }).find().skip((page - 1) * limit).limit(limit);
    // 判断数据是否还有
    let searchStatus = true
    if (page * limit >= seaTotal) {
        searchStatus = false
    }
    res.json({
        "total": seaTotal,
        "list": seaResult,
        "dataStatus": searchStatus
    })
}

module.exports = {
    postArticle,
    allArticle,
    userArticle,
    searchArticle
}